#include "login.h"
#include "ui_login.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkReply>
#include <qmessagebox.h>
#include <QMouseEvent>
#include <Utils\DataVerification.h>

Login::Login(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Login)
{
    setWindowFlags(Qt::FramelessWindowHint | Qt::WindowMinimizeButtonHint);
    ui->setupUi(this);
    user_request = new UserRequest(this);
    connect(user_request,&UserRequest::regFinished,this,&Login::requestFinished);
    connect(user_request,&UserRequest::loginFinished,this,&Login::loginFinished);
}

Login::~Login()
{
    delete ui;
}

void Login::on_loginButton_clicked()
{
    QString name = ui->nameLineEdit->text();
    QString pwd = ui->passwordLineEdit->text();
    QJsonObject obj;
    obj["name"] = name;
    obj["password"] = pwd;
    QJsonDocument doc(obj);
    user_request->login(doc.toJson());
}

void Login::requestFinished(QJsonObject obj)
{
    int code = obj["code"].toInt();
    if(code == 1){
        QMessageBox::information(this,"注册提示","注册成功");
    }else{
        QMessageBox::information(this,"注册提示",obj["msg"].toString());
    }
}

void Login::loginFinished(QJsonObject obj)
{
    int code = obj["code"].toInt();
    if(code == 1){
        page = new ChatInterface(obj["data"].toInt());
        close();
        page->show();
    }else{
        QMessageBox::information(this,"登录失败提示2",obj["msg"].toString());
    }
}

void Login::on_pushButton_clicked()
{
    ui->stackedWidget->setCurrentIndex(1);
}

void Login::on_toolButton_3_clicked()
{
    this->close();
}

void Login::on_pushButton_2_clicked()
{
    ui->stackedWidget->setCurrentIndex(0);
}

void Login::on_regButton_clicked()
{
    QString name = ui->usernameEdit->text();
    QString pwd = ui->passwordEdit->text();
    QString phone = ui->phoneEdit->text();
    if(!DataVerification::CheckPhoneNumber(phone.size(), phone)){
        QMessageBox::information(this,"注册提示","电话格式错误");
        return;
    }
    QString gender;
    if(ui->manButton->isChecked())
    {
        gender = ui->manButton->text();
    }
    else if(ui->wemanButton->isChecked()){
        gender = ui->wemanButton->text();
    }
    QJsonObject obj;
    obj["username"]=name;
    obj["password"]=pwd;
    obj["phone"]=phone;
    obj["gender"]=gender;
    QJsonDocument doc(obj);
    user_request->reg(doc.toJson());
}
void Login::mouseMoveEvent(QMouseEvent *e)
{
    if(is_drag){
        move(e->globalPosition().toPoint() - start_pos);
    }
}

void Login::mousePressEvent(QMouseEvent *e)
{
    start_pos = e->pos();
    if(start_pos.y() < 30){
        is_drag = true;
    }else{
        is_drag = false;
    }
}

void Login::on_toolButton_2_clicked()
{
    this->showMinimized();
}

void Login::on_toolButton_clicked()
{
    this->close();
}

void Login::on_toolButton_4_clicked()
{
     this->showMinimized();
}

